<template>
  <dark-mode-container>
    <div f-y-c>
      <icon mr-15 text-18 icon="nimbus:edit" />
      <span text-16>编辑菜单：{{ isDelete ? "" : menu?.name }}</span>
    </div>
    <n-divider />
    <n-alert type="info" closable> 从菜单列表选择一项后，进行编辑</n-alert>

    <n-card :bordered="false" v-if="!isDelete">
      <catalog-form
        ref="formRef"
        type="edit"
        :data="menu"
        v-if="menu?.type === 0"
        @submit-success="emits('submitSuccess')"
      />
      <page-form
        ref="formRef"
        type="edit"
        :data="menu"
        v-else-if="menu?.type === 1"
        @submit-success="emits('submitSuccess')"
      />
      <button-form
        ref="formRef"
        type="edit"
        :data="menu"
        v-else-if="menu?.type === 2"
        @submit-success="emits('submitSuccess')"
      />
      <n-space v-if="menu" ml-100>
        <n-button type="warning" @click="handleSubmit">保留修改</n-button>
        <n-button @click="handleReset">取消修改</n-button>
        <n-button type="error" @click="handleDelete">删除</n-button>
      </n-space>
    </n-card>
  </dark-mode-container>
</template>

<script lang="tsx" setup>
import { Icon } from "@iconify/vue";
import ButtonForm from "../menu-form/button.vue";
import PageForm from "../menu-form/page.vue";
import CatalogForm from "../menu-form/catalog.vue";
import { menuApi } from "@/api";

interface Props {
  menu?: Menu;
}
interface Emits {
  (e: "submitSuccess"): void;
  (e: "removeSuccess"): void;
}
const props = defineProps<Props>();
const emits = defineEmits<Emits>();

const formRef = ref();
const isDelete = ref(false);

watch(
  () => props.menu,
  () => {
    isDelete.value = false;
  }
);

const handleSubmit = async () => {
  await formRef.value.valid();
  const dialog = window.$dialog.warning({
    title: "警告",
    content: `确定修改【${props.menu?.name}】吗？`,
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: async () => {
      dialog.loading = true;
      try {
        await formRef.value.handleSubmit();
      } finally {
        dialog.loading = false;
      }
    },
  });
};

const handleReset = () => {
  formRef.value.handleReset();
};

const handleDelete = () => {
  const dialog = window.$dialog.error({
    title: "警告",
    content: `确定删除【${props.menu?.name}】吗？`,
    positiveText: "确定",
    negativeText: "取消",
    icon: () => <Icon icon="dashicons:warning"></Icon>,
    onPositiveClick: async () => {
      dialog.loading = true;
      try {
        const { status } = await menuApi.remove(props.menu!.id!);
        if (status) {
          window.$message.success("删除成功");
          isDelete.value = true;
          emits("removeSuccess");
        }
      } finally {
        dialog.loading = false;
      }
    },
  });
};
</script>
